#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# cron: 11 11 * * *
# const $ = new Env("大潮红包推送");
import os
import re
import glob
import time
import json
import logging
from datetime import datetime, timedelta
from wechat_test import wechat_sender

# 日志目录配置
LOG_DIR = "/ql/data/log/"
LOG_PATTERN = "DaChao_*"
# 报告保存路径
REPORT_DIR = "/ql/data/log/Message/"
REPORT_FILE = os.path.join(REPORT_DIR, "PUSH_dachao.log")
# 历史数据保存路径
HISTORY_FILE = os.path.join(REPORT_DIR, "PUSH_dachao_history.json")

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger("DaChaoReport")

# 修复：重构红包提取逻辑，支持多红包
def extract_redpackets(log_content):
    """
    从日志内容中提取红包信息，支持多红包
    返回格式: {手机号: [(金额, code), ...]}
    """
    # 匹配用户开始行: "用户：174****4233开始任务"
    user_pattern = re.compile(r"用户：(\d{11})开始任务")
    # 增强红包匹配正则，支持多种格式
    redpacket_pattern = re.compile(
        r"奖品：.*?(微信现金红包|(\d+\.?\d*)\s*元).*?code：([A-Za-z0-9]+)"
    )
    
    # 存储结果
    user_redpackets = {}
    current_user = None
    
    # 按用户存储已处理的code（防止单日志文件内重复）
    user_processed_codes = {}
    
    for line in log_content.split('\n'):
        # 检测用户开始 - 不重置红包集合
        user_match = user_pattern.search(line)
        if user_match:
            current_user = user_match.group(1)
            if current_user not in user_redpackets:
                user_redpackets[current_user] = []
                user_processed_codes[current_user] = set()
            continue
        
        # 检测红包信息
        if current_user:
            redpacket_match = redpacket_pattern.search(line)
            if redpacket_match:
                # 处理金额格式
                amount_str = redpacket_match.group(2)
                if not amount_str:  # 如果是"微信现金红包"格式
                    amount = "0.00"  # 默认金额
                else:
                    amount = amount_str
                    # 确保金额格式正确
                    if '.' not in amount:
                        amount = amount[:-1] + '.' + amount[-1] if len(amount) > 1 else amount + ".00"
                
                code = redpacket_match.group(3)
                
                # 检查该用户是否已处理过该code（当日志内重复时）
                if code not in user_processed_codes.get(current_user, set()):
                    user_redpackets.setdefault(current_user, []).append((amount, code))
                    user_processed_codes.setdefault(current_user, set()).add(code)
                    print(f"  + 用户 {current_user} 发现红包: {amount}元, code: {code}")
                else:
                    print(f"  - 用户 {current_user} 跳过重复红包: {amount}元, code: {code}")
    
    return user_redpackets

# 获取最近24小时的日志文件
def get_recent_logs():
    """获取24小时内修改过的日志文件"""
    now = time.time()
    logs = []
    
    # 1. 获取所有DaChao_开头的目录
    dachao_dirs = glob.glob(os.path.join(LOG_DIR, "DaChao_*"))
    
    for dachao_dir in dachao_dirs:
        # 只处理目录
        if not os.path.isdir(dachao_dir):
            continue
            
        # 2. 获取目录中的所有日志文件
        for file in os.listdir(dachao_dir):
            file_path = os.path.join(dachao_dir, file)
            
            # 只处理文件
            if not os.path.isfile(file_path):
                continue
                
            # 检查修改时间
            if now - os.path.getmtime(file_path) < 86400:  # 24小时
                logs.append(file_path)
    
    # 3. 检查根目录下的日志文件（如果有）
    for file in glob.glob(os.path.join(LOG_DIR, "*.log")):
        if os.path.isfile(file) and (now - os.path.getmtime(file) < 86400):
            logs.append(file)
            
    return logs

# 生成企业微信消息内容
def generate_message(redpackets):
    """根据红包信息生成消息内容"""
    if not redpackets:
        return "未发现需要领取的红包"
        
    message = "大潮重要通知：\n1. 请及时领取\n2. 链接有效期24小时\n"
    
    for i, (amount, code) in enumerate(redpackets, 1):
        # 处理默认金额显示
        display_amount = amount if amount != "0.00" else "随机金额"
        message += (
            f"3.{i} 微信红包【{display_amount}】点击进入领取："
            f"https://m.aihoge.com/lottery/rotor/drawRedPacket?CHECK_CODE={code}\n"
        )
    
    return message.strip()

# 生成汇总通知内容（简化版）
def generate_summary_message(user_stats):
    """
    生成汇总通知内容（简化版）
    user_stats: [(手机号, 备注, 红包数量, 总金额), ...]
    """
    if not user_stats:
        return "今日无红包记录"
    
    # 计算整体统计
    total_users = len(user_stats)
    total_redpackets = sum(count for _, _, count, _ in user_stats)
    total_amount = sum(amount for _, _, _, amount in user_stats)
    
    # 构建消息（简化格式）
    message = "💰 大潮红包汇总通知\n"
    message += f"📊 当日共{total_users}用户获得红包{total_redpackets}个，合计{total_amount:.2f}元\n"
    
    for i, (phone, remark, count, amount) in enumerate(user_stats, 1):
        # 简化格式：移除手机号和表情符号，简化文字描述
        message += f"{i}、【{remark}】获{count}红包共{amount:.2f}元\n"
    
    message += "⏰ 请及时领取红包"
    return message

# 发送企业微信通知
def send_wechat_notification(receiver_id, message, remark=None):
    """通过消息模块发送通知"""
    if not message:
        if remark:
            print(f"🟡 用户 {remark} 未发现需要通知的红包信息")
        else:
            print(f"🟡 未发现需要通知的红包信息")
        return False
        
    if remark:
        print(f"📤 发送通知给 {remark} ({receiver_id})...")
    else:
        print(f"📤 发送汇总通知给 {receiver_id}...")
    
    success = wechat_sender.send_message(receiver_id, message)
    
    if success:
        if remark:
            print(f"✅ {remark} 通知发送成功")
        else:
            print(f"✅ 通知发送成功")
    else:
        if remark:
            print(f"❌ {remark} 通知发送失败")
        else:
            print(f"❌ 通知发送失败")
            
    return success

# 解析接收人配置 (新格式)
def parse_receiver_config():
    """解析接收人配置环境变量"""
    receiver_config = os.environ.get("QYWX_RECEIVER")
    if not receiver_config:
        print("🟡 未设置个人通知接收人环境变量 QYWX_RECEIVER")
        return {}
    
    config_dict = {}
    lines = receiver_config.strip().split('\n')
    
    for line in lines:
        line = line.strip()
        if not line:
            continue
            
        parts = line.split('#')
        if len(parts) >= 3:
            receiver_id = parts[0].strip()
            phone = parts[1].strip()
            remark = parts[2].strip()
            config_dict[phone] = (receiver_id, remark)
        else:
            print(f"⚠️ 忽略无效的个人通知配置行: {line}")
    
    return config_dict

# 解析汇总接收人配置 (使用新的分隔符)
def parse_summary_receiver_config():
    """解析汇总接收人配置"""
    summary_config = os.environ.get("QYWX_SUMMARY_RECEIVER")
    if not summary_config:
        print("🟡 未设置汇总接收人环境变量 QYWX_SUMMARY_RECEIVER")
        return []
    
    summary_receivers = []
    lines = summary_config.strip().split('\n')
    
    for line in lines:
        line = line.strip()
        if not line:
            continue
            
        # 新格式: 接收人ID|用户手机号1#备注1|用户手机号2#备注2
        # 使用 '|' 作为用户块分隔符
        parts = line.split('|')
        if len(parts) < 2:
            print(f"⚠️ 忽略无效的汇总通知配置行: {line}")
            continue
            
        receiver_id = parts[0].strip()
        user_list = []
        
        # 处理每个用户块 (从第二个元素开始)
        for user_block in parts[1:]:
            # 用户块格式: 手机号#备注
            user_parts = user_block.split('#')
            if len(user_parts) >= 2:
                phone = user_parts[0].strip()
                remark = user_parts[1].strip()
                user_list.append((phone, remark))
            else:
                print(f"⚠️ 忽略无效的用户块: {user_block}")
        
        if receiver_id and user_list:
            summary_receivers.append((receiver_id, user_list))
            print(f"✅ 解析汇总配置: 接收人 {receiver_id} 有 {len(user_list)} 个用户")
        else:
            print(f"⚠️ 汇总接收人配置无效: {line}")
    
    return summary_receivers

# 生成详细报告
def generate_detailed_report(all_redpackets, receiver_config, logs, repeated_codes=None):
    """生成详细报告内容"""
    report = [
        "=" * 60,
        "大潮红包推送统计报告",
        "=" * 60,
        f"📅 报告时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
        f"📂 分析日志: {len(logs)} 个文件",
        "-" * 60
    ]
    
    # 添加日志文件列表
    report.append("📝 日志文件列表:")
    for log in logs:
        report.append(f"  - {os.path.basename(log)}")
    report.append("-" * 60)
    
    # 整体统计
    total_users = len(all_redpackets)
    total_redpackets = sum(len(packets_list) for packets_list in all_redpackets.values())
    total_amount = sum(sum(float(amount) for amount, _ in packets_list) for packets_list in all_redpackets.values())
    
    report.append(f"📊 整体统计:")
    report.append(f"  • 用户总数: {total_users}")
    report.append(f"  • 红包总数: {total_redpackets}")
    report.append(f"  • 总金额: {total_amount:.2f}元")
    
    # 添加重复红包统计
    if repeated_codes:
        report.append(f"  • 重复红包: {len(repeated_codes)}个")
    report.append("-" * 60)
    
    # 用户详情
    report.append("👤 用户详情:")
    for i, (phone, packets) in enumerate(all_redpackets.items(), 1):
        # 获取用户备注
        remark = ""
        if phone in receiver_config:
            _, remark = receiver_config[phone]
        
        user_amount = sum(float(amount) for amount, _ in packets)
        report.append(f"{i}. 【{remark or phone}】")
        report.append(f"   • 红包数量: {len(packets)}")
        report.append(f"   • 总金额: {user_amount:.2f}元")
        
        # 添加每个红包详情
        for j, (amount, code) in enumerate(packets, 1):
            # 处理默认金额显示
            display_amount = amount if amount != "0.00" else "随机金额"
            report.append(f"   • 红包{j}: {display_amount}元 (code: {code})")
    
    # 添加重复红包详情
    if repeated_codes:
        report.append("-" * 60)
        report.append("🔁 重复红包详情 (连续三天出现):")
        for i, (key, data) in enumerate(repeated_codes.items(), 1):
            report.append(f"{i}. 用户 {data['phone']}: code={data['code']}")
            report.append(f"   出现日期: {', '.join(sorted(data['dates']))}")
    
    return "\n".join(report)

# 保存报告到文件
def save_report(report_content):
    """保存报告到文件"""
    try:
        # 确保目录存在
        os.makedirs(REPORT_DIR, exist_ok=True)
        
        with open(REPORT_FILE, 'w', encoding='utf-8') as f:
            f.write(report_content)
        logger.info(f"报告已保存至: {REPORT_FILE}")
        return True
    except Exception as e:
        logger.error(f"保存报告失败: {str(e)}")
        return False

# 保存历史数据
def save_history_data(redpacket_data):
    """保存历史红包数据"""
    try:
        history_data = {}
        if os.path.exists(HISTORY_FILE):
            with open(HISTORY_FILE, 'r', encoding='utf-8') as f:
                history_data = json.load(f)
        
        # 使用当前日期作为键
        date_str = datetime.now().strftime('%Y%m%d')
        history_data[date_str] = redpacket_data
        
        with open(HISTORY_FILE, 'w', encoding='utf-8') as f:
            json.dump(history_data, f, ensure_ascii=False, indent=2)
        logger.info(f"历史数据已保存: {HISTORY_FILE}")
        return True
    except Exception as e:
        logger.error(f"保存历史数据失败: {str(e)}")
        return False

# 加载历史数据
def load_history_data(days=2):
    """加载指定天数的历史数据"""
    history_data = {}
    try:
        if os.path.exists(HISTORY_FILE):
            with open(HISTORY_FILE, 'r', encoding='utf-8') as f:
                all_history = json.load(f)
                
                # 获取最近N天的日期
                dates = sorted(all_history.keys(), reverse=True)[:days]
                for date in dates:
                    history_data[date] = all_history[date]
                    
                logger.info(f"加载 {len(history_data)} 天的历史数据")
        else:
            logger.info("无历史数据文件")
    except Exception as e:
        logger.error(f"加载历史数据失败: {str(e)}")
    
    return history_data

# 检测连续三天重复的红包
def detect_repeated_codes(current_data, history_data):
    """
    检测连续三天重复的红包
    返回: { (手机号, code): {phone: str, code: str, dates: [str]} }
    """
    # 首次运行时不进行过滤
    if not history_data:
        print("🟡 无历史数据，跳过重复红包检测")
        return {}
    
    # 合并当前数据和历史数据
    all_data = history_data.copy()
    current_date = datetime.now().strftime('%Y%m%d')
    all_data[current_date] = current_data
    
    # 按手机号和code分组
    code_occurrences = {}
    
    # 遍历所有日期的数据
    for date, date_data in all_data.items():
        for phone, packets in date_data.items():
            for amount, code in packets:
                key = (phone, code)
                if key not in code_occurrences:
                    code_occurrences[key] = set()
                code_occurrences[key].add(date)
    
    # 检测连续三天出现的红包
    repeated_codes = {}
    today = datetime.now()
    
    for key, dates in code_occurrences.items():
        # 如果日期少于3天，直接跳过
        if len(dates) < 3:
            continue
            
        # 将日期字符串转换为日期对象并排序
        sorted_dates = sorted([datetime.strptime(d, '%Y%m%d') for d in dates])
        
        # 检查是否有连续三天的记录
        for i in range(len(sorted_dates) - 2):
            date1 = sorted_dates[i]
            date2 = sorted_dates[i+1]
            date3 = sorted_dates[i+2]
            
            # 检查是否连续三天
            if (date2 - date1 == timedelta(days=1)) and (date3 - date2 == timedelta(days=1)):
                phone, code = key
                # 记录所有出现日期
                all_date_strs = [d.strftime('%Y-%m-%d') for d in sorted_dates]
                repeated_codes[f"{phone}_{code}"] = {
                    "phone": phone,
                    "code": code,
                    "dates": all_date_strs
                }
                print(f"⚠️ 检测到连续三天重复红包: 用户 {phone}, code: {code}")
                break  # 找到一组即可
    
    if not repeated_codes:
        print("✅ 未检测到连续三天重复的红包")
    return repeated_codes

# 主函数
def main():
    print("="*50)
    print("大潮红包监控通知脚本启动")
    print(f"时间: {time.strftime('%Y-%m-%d %H:%M:%S')}")
    
    # 解析接收人配置
    receiver_config = parse_receiver_config()
    
    if receiver_config:
        print("\n🔧 个人通知配置信息:")
        for phone, (receiver_id, remark) in receiver_config.items():
            print(f"接收人ID: {receiver_id} -> 手机号: {phone} ({remark})")
    else:
        print("\n🟡 未配置个人通知接收人")
    
    # 解析汇总接收人配置
    summary_receivers = parse_summary_receiver_config()
    if summary_receivers:
        print("\n📊 汇总通知配置信息:")
        for i, (receiver_id, user_list) in enumerate(summary_receivers, 1):
            print(f"汇总接收人 {i}: {receiver_id}")
            for j, (phone, remark) in enumerate(user_list, 1):
                print(f"  {j}. 手机号: {phone} ({remark})")
    else:
        print("\n🟡 未配置汇总通知接收人")
    
    # 加载历史数据（最近2天）
    history_data = load_history_data(days=2)
    
    # 获取日志内容
    logs = get_recent_logs()
    if not logs:
        print("\n🟡 未找到24小时内的日志文件")
        # 生成空报告
        empty_report = "大潮红包推送报告\n\n未找到24小时内的日志文件"
        save_report(empty_report)
        return
        
    print(f"\n📂 找到 {len(logs)} 个日志文件:")
    for log in logs:
        print(f"  - {log}")
    
    # 读取所有日志内容
    all_content = ""
    for log_file in logs:
        try:
            with open(log_file, 'r', encoding='utf-8') as f:
                content = f.read()
                print(f"📄 读取 {os.path.basename(log_file)} ({len(content)} 字节)")
                all_content += content + "\n"
        except Exception as e:
            print(f"⚠️ 读取日志失败 {log_file}: {str(e)}")
    
    # 提取所有用户的红包信息
    print("\n🔍 提取红包信息:")
    all_redpackets = extract_redpackets(all_content)
    
    # 记录红包总数
    total_redpackets = sum(len(packets) for packets in all_redpackets.values())
    print(f"\n🔍 红包统计: 共发现 {len(all_redpackets)} 用户, {total_redpackets} 个红包")
    
    if not all_redpackets:
        print("未发现任何红包信息")
        # 生成空报告
        empty_report = "大潮红包推送报告\n\n未发现任何红包信息"
        save_report(empty_report)
        return
    
    # 保存当前红包数据到历史记录
    save_history_data(all_redpackets)
    
    # 检测连续三天重复的红包
    repeated_codes = detect_repeated_codes(all_redpackets, history_data)
    
    # 发送个人通知给配置的用户
    notifications_sent = 0
    for phone, redpackets in all_redpackets.items():
        # 首次运行时不进行过滤
        filtered_redpackets = redpackets
        
        # 如果检测到重复红包，进行过滤
        if repeated_codes:
            filtered_redpackets = []
            for amount, code in redpackets:
                is_repeated = any(
                    rep_info["phone"] == phone and rep_info["code"] == code 
                    for rep_info in repeated_codes.values()
                )
                if not is_repeated:
                    filtered_redpackets.append((amount, code))
                else:
                    print(f"🔇 过滤连续三天重复红包: 用户 {phone}, {amount}元, code: {code}")
        
        # 发送个人通知（如果配置了接收人）
        if phone in receiver_config:
            receiver_id, remark = receiver_config[phone]
            message = generate_message(filtered_redpackets)
            
            print(f"\n📱 用户 {phone} ({remark}) 有 {len(filtered_redpackets)} 个红包待领取")
            if len(filtered_redpackets) > 0:
                print(f"🎁 红包详情:")
                total_amount = 0
                for amount, code in filtered_redpackets:
                    display_amount = amount if amount != "0.00" else "随机金额"
                    print(f"  - {display_amount}: {code}")
                    total_amount += float(amount)
            
            if send_wechat_notification(receiver_id, message, remark):
                notifications_sent += 1
        else:
            print(f"⚠️ 用户 {phone} 未配置个人接收人，跳过通知")
    
    # 发送汇总通知
    summary_notifications_sent = 0
    if summary_receivers:
        for receiver_id, user_list in summary_receivers:
            # 收集汇总通知所需的用户统计
            summary_stats = []
            for phone, remark in user_list:
                if phone in all_redpackets:
                    # 使用过滤后的红包数据
                    user_redpackets = all_redpackets[phone]
                    total_amount = sum(float(amount) for amount, _ in user_redpackets)
                    summary_stats.append((phone, remark, len(user_redpackets), total_amount))
                    print(f"📊 汇总用户 {phone} ({remark}) 有 {len(user_redpackets)} 红包，共计 {total_amount:.2f}元")
                else:
                    print(f"📊 汇总用户 {phone} ({remark}) 无日志记录")
            
            # 发送汇总通知
            if summary_stats:
                summary_message = generate_summary_message(summary_stats)
                print(f"\n📊 生成汇总通知给 {receiver_id}:")
                print(summary_message)
                if send_wechat_notification(receiver_id, summary_message, f"汇总通知给 {receiver_id}"):
                    summary_notifications_sent += 1
            else:
                print(f"🟡 无有效用户数据，跳过发送汇总通知给 {receiver_id}")
    
    # 生成并保存详细报告
    detailed_report = generate_detailed_report(all_redpackets, receiver_config, logs, repeated_codes)
    save_report(detailed_report)
    print(f"\n📝 已生成详细报告: {REPORT_FILE}")
    
    print(f"\n✅ 完成! 共发送 {notifications_sent} 条个人通知")
    if summary_receivers:
        print(f"     和 {summary_notifications_sent} 条汇总通知")
    print("="*50)

if __name__ == "__main__":
    main()